# -*- coding:utf-8 -*-
import logging

from mq import BaseConsumer
from util.date_util import curr_now
from util.mail_sender import MailSender

logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(name)s %(levelname)s lineno:%(lineno)d %(message)s")
logger = logging.getLogger('mq.consumer.code.mail')

class CodeMailNotice(BaseConsumer):

    def init(self):
        self.mail = MailSender()


    def _get_admin(self, staff_id):
        admins = self.db.query("select email, mobile, company_id from t_staff "
                               " where company_id "
                               "    in (select company_id from t_staff where id=%(staff_id)s) "
                               "   and role_type=2", staff_id=staff_id)

        return admins[0] if admins else None

    def _get_surplus_total(self, company_id):
        return self.db.get("select count(*) cnt "
                           "  from t_abmap  "
                           " where company_id = %(company_id)s "
                           "   and expire_time > now() "
                           "   and allot_id = '' ", company_id=company_id)

    def _get_surplus_expire(self, company_id):
        return self.db.get("select count(*) cnt "
                           "  from t_abmap  "
                           " where company_id = %(company_id)s "
                           "   and expire_time > now() "
                           "   and DATE_SUB(expire_time, INTERVAL 30 DAY) < now() "
                           "   and allot_id = '' ", company_id=company_id)

    def _get_abmap(self, allot_id):
        """
        | id          | varchar(32)  | NO   | PRI | NULL    |       |
        | ida         | varchar(8)   | NO   |     | 0       |       |
        | idb         | varchar(8)   | NO   |     | 0       |       |
        | passwd      | varchar(8)   | NO   |     | 0       |       |
        | company_id  | varchar(32)  | NO   | MUL |         |       |
        | expire_time | datetime     | YES  | MUL | NULL    |       |
        | staff_id    | varchar(32)  | NO   | MUL |         |       |
        | allot_id    | varchar(32)  | NO   |     |         |       |
        | allot_time  | datetime     | YES  | MUL | NULL    |       |
        | create_date | datetime     | YES  |     | NULL    |       |
        | update_date | datetime     | YES  |     | NULL    |       |
        | remarks     | varchar(255) | YES  |     | NULL    |       |
        | del_flag    | char(1)      | YES  |     | 0       |       |

        :param allot_id:
        :return:
        """
        return self.db.query("select ab.id, ab.ida, ab.idb, ab.passwd, ab.allot_time, s.name, s.email, s.mobile "
                              "  from t_abmap ab "
                              "  left join t_staff s "
                              "    on s.id = ab.staff_id "
                              " where ab.allot_id=%(allot_id)s ", allot_id=allot_id)

    def _prepare_mail_txt(self, data, surplus_total_cnt, surplus_30day_expire_cnt):
        """
        提取通知
        dataObject.put("allotId", allotId);
        dataObject.put("staffId", staffId);
        dataObject.put("opEmail", opEmail);

        :param data:
        :return:
        """
        html = u''

        html += u'<p><table id="tab" style="width:600px;" cellpadding="2" cellspacing="0" align="center" border="1" bordercolor="#000000">'
        html += u'<tbody><tr>'
        html += u'<td style="text-align:center;font-size:14px;">提取码</td>'
        html += u'<td style="text-align:center;font-size:14px;">兑换码</td>'
        html += u'<td style="text-align:center;font-size:14px;">密码</td>'
        html += u'<td style="text-align:center;font-size:14px;">提取时间</td>'
        html += u'<td style="text-align:center;font-size:14px;">操作人</td></tr>'

        abmaps = self._get_abmap(data.allotId)
        for abmap in abmaps:
            html += u'<tr>'
            html += u'<td style="text-align:center;font-size:14px;">{}</td>'.format(abmap.ida)
            html += u'<td style="text-align:center;font-size:14px;">{}</td>'.format(abmap.idb)
            html += u'<td style="text-align:center;font-size:14px;">{}</td>'.format(abmap.passwd)
            html += u'<td style="text-align:center;font-size:14px;">{}</td>'.format(abmap.allot_time)
            html += u'<td style="text-align:center;font-size:14px;">{}</td>'.format(abmap.name)
            html += u'</tr>'

        html += u'</tbody></table></p>'

        html += u'<p></p>'
        html += u'<p></p>'
        html += u'<p>未被提取总共剩余：{}个</p>'.format(surplus_total_cnt.cnt)
        html += u'<p>最近30天内将要过期的兑换码数量：{}个</p>'.format(surplus_30day_expire_cnt.cnt)

        return html


    def runner(self, data):
        """
        dataObject.put("allotId", allotId);
        dataObject.put("staffId", staffId);
        dataObject.put("opEmail", opEmail);
        :param data:
        :return:
        """


        admin = self._get_admin(data.staffId)

        receivers = []
        if data.opEmail:
            receivers.append(data.opEmail)

        if admin:
            receivers.append(admin.email)

        if not receivers:
            logger.debug("receivers is empty")
            return True

        surplus_total_cnt = self._get_surplus_total(data.companyId)
        surplus_30day_expire_cnt = self._get_surplus_expire(data.companyId)

        html = self._prepare_mail_txt(data, surplus_total_cnt, surplus_30day_expire_cnt)

        subject = u'兑换码提取成功-{}'.format(curr_now())
        self.mail._send_mail(receivers, subject, html)

        return True